import React, { Component } from 'react'

import { SearchBar } from 'antd-mobile'

import debounce from 'lodash/debounce'

import { getCurrentCity, API } from '../../../utils'

import styles from './index.module.css'

export default class Search extends Component {
  // 当前城市id
  // cityId = getCurrentCity().value
  async componentDidMount() {
    const {value}= await getCurrentCity()
    this.cityId = value
    // console.log(this.cityId);
  }
  state = {
    // 搜索框的值
    searchTxt: '',
    tipsList: []
  }

  // 渲染搜索结果列表
  renderTips = () => {
    const { tipsList } = this.state

    return tipsList.map(item => (
      <li key={item.community} className={styles.tip} onClick={() => {
        const {community, communityName} = item
        // replace的第二个参数为要传给跳转页面的数据
        this.props.history.replace('/rent/add', {
          community,
          communityName
        })
      }}>
        {item.communityName}
      </li>
    ))
  }
  handleChange = async value => {
    // 没输入一个字符就发送一次请求，频繁请求响应不合理， 需做防抖处理
    this.setState({ searchTxt: value})
    // 根据用户输入的关键词查询小区信息
    // const res = await API.get('/area/community', {
    //   params: {
    //     name: value,
    //     id: this.cityId
    //   }
    // })
    // console.log(res);
    this.getCommunityList(value)
  }
  // lodash库封装的防抖函数debounce
  getCommunityList = debounce(async value => {
    const {data: {body}} = await API.get('/area/community', {
      params: {
        name: value,
        id: this.cityId
      }
    })
    // console.log(res);
    this.setState({tipsList: body})
  }, 500)
  render() {
    const { history } = this.props
    const { searchTxt } = this.state

    return (
      <div className={styles.root}>
        {/* 搜索框 */}
        <SearchBar
          className="search"
          placeholder="请输入小区或地址"
          value={searchTxt}
          showCancelButton={true}
          onCancel={() => history.replace('/rent/add')}
          onChange={this.handleChange}
        />

        {/* 搜索提示列表 */}
        <ul className={styles.tips}>{this.renderTips()}</ul>
      </div>
    )
  }
}
